package com.goldenautumn.prefabricate.widget.dialog

import android.view.Gravity
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.view.animation.AnimationUtils
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.fragment.app.viewModels
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.Utils
import com.blankj.utilcode.util.VibrateUtils
import com.goldenautumn.prefabricate.R
import com.goldenautumn.prefabricate.activity.account.PhoneLoginActivity
import com.goldenautumn.prefabricate.business.entity.OrderMenuInfoVo
import com.goldenautumn.prefabricate.business.user.LoadingUiState
import com.goldenautumn.prefabricate.business.user.LoginUiState
import com.goldenautumn.prefabricate.business.user.UserInfoUiState
import com.goldenautumn.prefabricate.business.user.UserViewModel
import com.goldenautumn.prefabricate.databinding.DialogEditInfoBinding
import com.goldenautumn.prefabricate.utils.Constants
import com.goldenautumn.prefabricate.utils.getUserInfo
import com.goldenautumn.prefabricate.utils.loadImgUrl
import com.goldenautumn.prefabricate.utils.onCenterToast
import kotlinx.coroutines.isActive
import kotlinx.coroutines.selects.select
import qncx.external.common.compat.isVisible
import qncx.external.common.compat.visible
import qncx.external.common.utils.ticker
import qncx.external.common.widget.dialog.BaseDialog
import java.util.concurrent.TimeUnit

class EditInfoDialog constructor(val type:Int,val block: () -> Unit) : BaseDialog<DialogEditInfoBinding>(qncx.external.common.R.style.BottomDialogs) {

    private val mUserModel by viewModels<UserViewModel>()

    private var time = 0

    override val layoutRes: Int
        get() = R.layout.dialog_edit_info

    override fun onStart() {
        super.onStart()
        val window: Window? = dialog?.window
        val params: WindowManager.LayoutParams? = window?.attributes
        params?.dimAmount = dimAmount
        params?.width = WindowManager.LayoutParams.MATCH_PARENT
        params?.height = (ScreenUtils.getScreenHeight() * 0.5).toInt()
        params?.gravity = Gravity.BOTTOM
        window?.attributes = params
    }

    override suspend fun bindView(view: View): View {
        mBinding.closeBtn.setOnClickListener { dismiss() }
        mBinding.constraintLayout9.isVisible(type == 1)
        mBinding.nickNameBody.isVisible(type == 2)
        mBinding.title.setText(if(type == 1) R.string.edit_phone else R.string.change_nickname)

        var userInfo = getUserInfo()
        userInfo.nickName?.let { mBinding.nickName.setText(userInfo.nickName) }

        mBinding.sendBtn.setOnClickListener {
            var phone = mBinding.phone.text.toString()
            if(phone.length == 11 ){
                time = 60
                mUserModel.getCode(phone,"10")
            } else {
                VibrateUtils.vibrate(50)
                mBinding.phone.startAnimation(AnimationUtils.loadAnimation(it.context, R.anim.shake_anim))
            }
        }

        mBinding.saveBtn.setOnClickListener {
            if(type == 1) {
                var phone = mBinding.phone.text.toString()
                var code = mBinding.code.text.toString()
                if(phone.length != 11 ) {
                    VibrateUtils.vibrate(50)
                    mBinding.phone.startAnimation(AnimationUtils.loadAnimation(it.context, R.anim.shake_anim))
                    mBinding.saveBtn.reset()
                    return@setOnClickListener
                }
                if(code.length < 6 ) {
                    VibrateUtils.vibrate(50)
                    mBinding.code.startAnimation(AnimationUtils.loadAnimation(it.context, R.anim.shake_anim))
                    mBinding.saveBtn.reset()
                    return@setOnClickListener
                }
                mUserModel.bindPone(phone,code)
            } else if(type == 2){
                var nickName = mBinding.nickName.text.toString()
                if(nickName.isNullOrEmpty()) {
                    VibrateUtils.vibrate(50)
                    mBinding.nickName.startAnimation(AnimationUtils.loadAnimation(it.context, R.anim.shake_anim))
                    mBinding.saveBtn.reset()
                    return@setOnClickListener
                }
                mUserModel.updateUserInfo(niceName = nickName)
            }
        }

        var ticker = ticker(TimeUnit.SECONDS.toMillis(1))
        while (isActive) {
            select {
                mUserModel.user.onReceive {
                    when(it) {
                        is UserInfoUiState.UserUpdate -> {
                            onCenterToast(it.msg ?: Utils.getApp().getString(R.string.update_success))
                            if(it.isSuccess) {
                                mBinding.saveBtn.showSucceed(500)
                                block()
                                mBinding.saveBtn.postDelayed({
                                    dismiss()
                                },50)
                            } else  mBinding.saveBtn.showError(500)
                        }
                        else -> {}
                    }
                }
                ticker.onReceive {
                    if(time == 0){
                        mBinding.sendBtn.isEnabled = true
                        mBinding.sendBtn.setText(R.string.get_verification)
                        mBinding.sendBtn.setTextColor(ContextCompat.getColor(mContext,R.color.colorPrimary))
                    } else {
                        --time
                        mBinding.sendBtn.isEnabled = false
                        mBinding.sendBtn.text = String.format(getString(R.string.get_verification_second),"$time")
                        mBinding.sendBtn.setTextColor(ContextCompat.getColor(mContext,R.color.colorPrimary77))
                    }
                }
            }
        }

        return view
    }
}